#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

int sem_take(sem_t *sem, int32_t timeout)
{
	struct timespec abs_time;
	
	if(timeout > 0)
	{
		if(clock_gettime(CLOCK_REALTIME, &abs_time) != 0)
			return -1;
		abs_time.tv_sec += timeout / 1000;
		abs_time.tv_nsec += (timeout % 1000) * 1000 * 1000;
		if(abs_time.tv_nsec >= (1*1000*1000*1000))
		{
			abs_time.tv_nsec -= 1 * 1000 * 1000 * 1000;
			abs_time.tv_sec += 1;
		}
		return sem_timedwait(sem, &abs_time);
	}
	else if(timeout == 0)
		return sem_trywait(sem);
	else
		return sem_wait(sem);
}

int sem_release(sem_t *sem)
{
	return sem_post(sem);
}

static sem_t sem;
static sem_t *p_sem;

void *thread1(void *arg)
{
	while(1)
	{
		if(sem_take(p_sem, -1) != 0)
			perror("sem_take:");
		else
			printf("sem_take succeed\r\n");
	}
}

void *thread2(void *arg)
{
	while(1)
	{
		if(sem_release(p_sem) != 0)
			perror("sem_release:");
		sleep(1);
	}
}

int main(int argv, char *argc[])
{
	int restul;
	void *exit_value;
	pthread_t tid1,tid2; 
	
//	//初始化无名信号量
//	if(sem_init(&sem, 0, 1) != 0)
//	{
//		perror("sem_init:");
//		return -1;
//	}
//	p_sem = &sem;
	
	//创建、打开有名信号量
	p_sem = sem_open("test.sem", O_CREAT, 0777, 0);
	if(p_sem == SEM_FAILED)
	{
		perror("sem_open:");
		return -1;
	}
	
	//创建线程
	restul = pthread_create(&tid1, NULL, thread1, "this thread1");
	if(restul != 0)
	{
		printf("pthread_create: error code %d\r\n", restul);
		return -1;
	}
	restul = pthread_create(&tid2, NULL, thread2, "this thread2");
	if(restul != 0)
	{
		printf("pthread_create: error code %d\r\n", restul);
		return -1;
	}
	
	//主线程不能退出
	while(1)
	{
		sleep(10);
	}
	
//	//脱离无名信号量
//	sem_destroy(&sem);

//	//关闭有名信号量
//	sem_close(p_sem);
//	//删除有名信号量
//	sem_unlink("./test.sem");
}
